package com.aijk.web.admin.controller.openapi;

import com.aijk.commons.file.FileServerFactory;
import com.aijk.web.admin.controller.openapi.entity.ApiResponse;
import com.aijk.web.admin.controller.openapi.entity.ext.UploadFile;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@Controller
public class UploadController extends ApiBaseController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    /**
     * 文件上传
     * @param
     * @return
     */
    @RequestMapping(path = "app/file/upload", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object companyList(@RequestParam MultipartFile files) {
        MultipartFile[] files1 = null;
        //获取文件扩展名
        if (files == null) {
            return new ApiResponse("-1", "上传文件不能为空");
        }else{
            files1 = new MultipartFile[]{files};
        }

        List<String> list = new ArrayList<>();

        for (MultipartFile file : files1) {

            //获取文件名
            String fileName = FilenameUtils.getName(file.getOriginalFilename());

            byte[] bytes;
            try {
                bytes = file.getBytes(); //将文件转换成字节流形式
            } catch (IOException e) {
                logger.error("上传文件异常", e);
                return new ApiResponse("-1", "上传文件不能为空");
            }
            //调用上传文件的具体方法
            com.aijk.base.entity.FileInfo uploadResult = FileServerFactory.get().uploadFile(bytes, fileName);

            list.add(uploadResult.getUrl());

        }
        UploadFile file = new UploadFile();
        if(list!=null && list.size()>0){
            file.setUrls(list.get(0));
        }
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setData(file);
        return apiResponse;
    }

}
